//
//  PullLayout.m
//  瀑布流封装
//
//  Created by 常宽 on 14/11/1.
//  Copyright (c) 2014年 常宽. All rights reserved.
//

#import "PullLayout.h"



@implementation PullLayout

- (void) prepareLayout
{
    [super prepareLayout];
    _attributesArrayOfCollectionView = [[NSMutableArray alloc] init];
    
    //获得section里有多少个item
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    //获得每一个item的属性设置
    
    float offYLeft = 2.5;
    float offYRight = 2.5;
    
    for (int i = 0; i < count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        //获得每个item的属性
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        //协议
        CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
        
        //根据单双数来获得x坐标
        float offX = 0;
        if (i % 2 == 0) {
            offX = 2.5;
        }else{
            offX = 1.5 + size.width + self.minimumInteritemSpacing;
        }
        
        //获得Y坐标
        if (i % 2 == 0) {
            att.frame = CGRectMake(offX, offYLeft, size.width, size.height);
            offYLeft += size.height + self.minimumLineSpacing;
        }else{
            att.frame = CGRectMake(offX, offYRight, size.width, size.height);
            offYRight += size.height + self.minimumLineSpacing;
        }
        [_attributesArrayOfCollectionView addObject:att];
    }
    
}

////返回每一个item的属性(不走)
//- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return _attributesArrayOfCollectionView[indexPath.item];
//}


//返回rect区域内的所有item的属性
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *currentArray = [NSMutableArray array];
    
    for (int i = 0; i < [_attributesArrayOfCollectionView count]; i++) {
        UICollectionViewLayoutAttributes *att = _attributesArrayOfCollectionView[i];
        
        
        //判断第二rect是不是在第一个rect的范围内
        if (CGRectIntersectsRect(rect, att.frame)) {
            [currentArray addObject:att];
        }
    }
    
    
    return currentArray;
}


@end
